<?php
declare(strict_types=1);

namespace Zms\AdminHelper;

use Hyperf\Context\ApplicationContext;
use Hyperf\HttpServer\Contract\RequestInterface;

class Request
{


    /**
     * 获取自身实例
     * @return Request
     */
    public static function instance(): Request
    {
        return ApplicationContext::getContainer()->get(self::class);
    }


    /**
     * 获取请求对象
     * @return RequestInterface
     */
    public function request(): RequestInterface
    {
        return ApplicationContext::getContainer()->get(RequestInterface::class);
    }


    /**
     * 整个HTTP请求中的全部信息
     * @author 竹林风@875384189 2022/1/14 10:28
     */
    public function wholeData(array $context = []): array
    {
        $request = $this->request();
        $whole = [
            'get' => $request->query(),
            'post' => $request->post(),
            'file' => [],
            'url' => $this->url(),
            'cookie' => $request->getCookieParams(),
            'header' => $request->getHeaders(),
            'context' => $context
        ];
        foreach ($request->getUploadedFiles() as $file) {
            $whole['file'][] = $file->toArray();
        }
        return $whole;
    }


    /**
     * 获取域名
     * @author 竹林风@875384189 2022/1/14 10:34
     */
    public function host(): string
    {
        return $this->request()->getUri()->getHost();
    }

    /**
     * 获取域名端口
     * @author 竹林风@875384189 2022/1/14 10:34
     */
    public function webPort(): int
    {
        return $this->request()->getUri()->getPort() ?? 80;
    }


    /**
     * 是否HTTP协议
     * @author 竹林风@875384189 2022/1/14 10:41
     */
    public function isHttps(): bool
    {
        $scheme = $this->request()->getHeader('x-forwarded-proto')[0] ?? '';
        return $scheme === 'https';
    }


    /**
     * 完整域名
     * @author 竹林风@875384189 2022/1/14 10:42
     */
    public function origin(): string
    {
        $port = $this->webPort();
        return ($this->isHttps() ? 'https://' : 'http://') . $this->host() . ($port === 80 ? '' : ":$port");
    }


    /**
     * 获取路劲
     * @return string
     * @author 竹林风@875384189 2022/1/14 11:14
     */
    public function path(): string
    {
        return $this->request()->getPathInfo();
    }


    /**
     * 获取地址URL
     * @param bool $showHost 是否显示域名
     * @return string
     * @author 竹林风@875384189 2022/1/14 10:55
     */
    public function url(bool $showHost = true): string
    {
        $request = $this->request();
        $url = ($showHost ? $this->origin() : '') . $this->path();
        if ($query = $request->getQueryString()) {
            $url .= '?' . $query;
        }
        return $url;
    }


    /**
     * 判断是否AJAX请求
     * @return bool
     */
    public function isAjax(): bool
    {
        $header = $this->request()->getHeader('x-requested-with');
        if (in_array('XMLHttpRequest', $header)) {
            return true;
        }
        return false;
    }
}